package xyz.mumuwei.youthcourseserver.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import xyz.mumuwei.youthcourseserver.common.lang.Const;
import xyz.mumuwei.youthcourseserver.pojo.User;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mumuwei
 */
@Slf4j
public class JwtTokenUtil {


    /**
     * @title 生成token
     */
    public static String generateToken(User user)
    {
        Date date = new Date(System.currentTimeMillis() + Const.TOKEN_EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(Const.TOKEN_KEY);
        // 设置头部信息
        Map<String, Object> header = new HashMap<>(3);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        return JWT.create()
                .withHeader(header)
                .withClaim("id", user.getId())
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 校验 token
     * @param token token
     * @return true校验通过 抛异常 不通过
     */
    public static boolean verify(String token)
    {
        Algorithm algorithm = Algorithm.HMAC256(Const.TOKEN_KEY);
        JWT.require(algorithm).build().verify(token);
        return true;
    }

    /**
     * @title 获取token中的用户id
     */
    public static Integer getUserId(String token)
    {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("id").asInt();
    }
}